<template>
  <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-position="left" label-width="0px" class="demo-ruleForm login-container">
    <h3 class="title">系统登录</h3>
    <el-form-item prop="username">
      <el-input type="text" v-model="ruleForm.username" auto-complete="off" placeholder="登录账号"></el-input>
    </el-form-item>
    <el-form-item prop="password">
      <el-input type="password" v-model="ruleForm.password" auto-complete="off" placeholder="登录密码"></el-input>
    </el-form-item>
    <el-checkbox v-model="checked" checked class="remember">记住密码</el-checkbox>
    <a href="javascript:" class="register-href" @click="goRegister">没有账号，立即注册</a>
    <div class="clear-both"></div>
    <el-form-item>
      <el-button type="primary" style="width:100%;" @click="loginAction" :loading="loading">登录</el-button>
    </el-form-item>
  </el-form>
</template>

<script>
export default {
  data () {
    return {
      loading: false,
      ruleForm: {
        username: '',
        password: ''
      },
      rules: {
        username: [
          {required: true, message: '请输入登录账号', trigger: 'blur'}
        ],
        password: [
          {required: true, message: '请输入登录密码', trigger: 'blur'}
        ]
      },
      checked: true
    }
  },
  methods: {
    loginAction () {
      this.$refs.ruleForm.validate((valid) => {
        if (!valid) return
        this.loading = true
        setTimeout(() => {
          this.loading = false
          if (this.ruleForm.username !== 'admin' || this.ruleForm.password !== '123456') {
            this.$message({
              message: '用户名或密码错误',
              showClose: true,
              type: 'error'
            })
            return
          }
          // 登录成功
          this.loginSuccess()
        }, 500)
      })
    },
    loginSuccess () { // 登录成功操作
      // 保存用户登录标识
      this.$request.token('user')
      // 本地存储用户名密码
      this.saveNameAndPassword()
      this.$message({
        message: '登录成功',
        type: 'success'
      })
      this.$router.push('/welcome')
    },
    saveNameAndPassword () { // 记住用户名密码操作
      if (this.checked) {
        this.$request.storage('login-username', this.ruleForm.username)
        this.$request.storage('login-password', this.ruleForm.password)
      } else {
        this.$request.storage('login-username', '')
        this.$request.storage('login-password', '')
      }
    },
    goRegister () {
      this.$router.push('/register')
    }
  },
  mounted () {
    let storageUsername = this.$request.storage('login-username')
    let storagePassword = this.$request.storage('login-password')
    if (storageUsername && storagePassword) {
      this.ruleForm.username = storageUsername
      this.ruleForm.password = storagePassword
    }
  }
}
</script>
